/**
 * 
 */
package edu.gtcfla.km.platform.appmodules.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.vsg.common.configration.PreferencesRegister;
import org.vsg.security.annotation.RegisterRequestPermissionStrategy;

/**
 * @author Bill Vison
 *
 */
@Controller
public class MainController {

	private final static Logger logger = LoggerFactory.getLogger(MainController.class);

	@Autowired(required = false)
	public PreferencesRegister preferencesRegister;
	
	
	@RequiresAuthentication
	@RequestMapping(value = "/index.htm")
	public String index(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		// --- not regist value ---
		if ( !preferencesRegister.isRegisted() ) {
			return "redirect:/config/setup/startSetting.htm";
		}



		return null; 

	}

	@RequiresUser	
	@RegisterRequestPermissionStrategy(
		value = "ui-index",
		skipCheck = true
	)	
	@RequestMapping(value = "/apps/km/{entry}" , method = RequestMethod.GET)
	public String entryMainPage(@PathVariable String entry , HttpServletRequest httpServletRequest , 
			HttpServletResponse httpResp ,
			@CookieValue("JSESSIONID") String jsessionIdValue ,
			HttpSession session) throws Exception {
		String url = httpServletRequest.getRequestURI();
		
		String sessId = "";
		
		int jesIdLoc = url.indexOf("JSESSIONID=") ;
		if (jesIdLoc > -1) {
			sessId = url.substring( jesIdLoc + "JSESSIONID=".length());
		} else {
			sessId = jsessionIdValue;
		}
		
		logger.info("current page session id : " + sessId );
		
		// --- set current session id to cookie ---

		httpServletRequest.setAttribute("sessionId",sessId);
		
		// --- get current session ---
		
		String theme  = "km";
		
		String viewPath = "/apps/" + theme + "/index";
		
		return viewPath;
	}
	
	
	
}
